import { createRouter, createWebHashHistory, type RouteLocationNormalized, type RouteLocationNormalizedLoaded, type RouteRecordRaw, type RouterOptions } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import NotFound from '@/components/NotFound.vue'
import TableView from '@/pages/index/views/TableView.vue'
import { ElMessageBox } from 'element-plus'

console.debug('import.meta.env.BASE_URL', import.meta.env.BASE_URL)
const router = createRouter({
  // history: createWebHistory(import.meta.env.BASE_URL),
  history: createWebHashHistory(import.meta.env.BASE_URL),
  // history: createWebHashHistory('/'),
  routes: [
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      alias: ['/', '/index']
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    },
    {
      path: '/form',
      name: 'form',
      component: () => import('@/pages/index/views/FormView.vue')
    },
    {
      path: '/notfound',
      name: 'NotFound',
      component: NotFound
    },
    {
      path: '/table-view',
      name: 'tableView',
      component: TableView
    },
    {
      path: '/userInfo',
      name: 'NotFound',
      meta: {
        needLogin: true
      },
      component: NotFound
    },
    // 所有未定义路由，全部重定向到404页
    // {
    //   path: '*',
    //   redirect: '/404'
    // }
    // ,
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: NotFound
    },
    {
      path: '/common-settings',
      name: 'commonSettings',
      component: () => import('@/pages/index/views/CommonSettings.vue')
    },
    {
      name: 'logout',
      path: '/logout',
      redirect: () => {
        location.href = '/login/'
      }
    }
  ] as RouteRecordRaw[]
} as RouterOptions)

// 路由前置守卫
router.beforeEach((to, from, next) => {
  console.debug('from', from, 'to', to)

  const { meta, name } = to
  const { isLogin } = meta
  // token不存在时跳转非登录页，重定向到登录页
  if (!isLogin && name !== 'Login' && localStorage.getItem('firstLoginDate') === null) {
    location.href = '/login/'
    // next({ path: '/login' })
    return
  } else {
    next()
  }
})

router.onError((error: any, to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded) => {
  console.error(error)
  if (String(error).includes('Failed to fetch dynamically imported module')) {
    ElMessageBox.alert('路径已失效，请重新加载页面后再来访问', {
      title: '提示'
    })
  }
  console.error('to', to)
  console.error('from', from)
})

export default router
